<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <link rel="stylesheet" type="text/css" href="font_Icon/iconfont.css">
    <link rel="stylesheet" type="text/css" href="css/chat.css">
    <style>
          .file-input {
            display: inline-block;
            box-sizing: border-box;
            width: 16px;
            /*width: 60px;
            height: 60px;*/
            opacity: 0;
            cursor: pointer;
          }
          .select-button {
              color: #fff;
              /*line-height: 60px;*/
              position: absolute;
             /* width: 60px;
              height: 60px;*/
              text-align: center;
              border: none;
          }
          #chat-tuxiang{
            width: 16px;
          }
          #select-button{
            margin:0;
            padding: 0;
          }
          #select-button>i{
            margin-top: 12px;
          }

    </style>

</head>
<body>

<div class="chatContainer">
    <div class="chatBtn">
        <i class="iconfont icon-xiaoxi1"></i>
    </div>
    <div class="chat-message-num">10</div>
    <div class="chatBox" ref="chatBox">
        <div class="chatBox-info">
            <div class="chatBox-kuang" ref="chatBoxkuang">
                <div class="chatBox-content">
                    <div class="chatBox-content-demo" id="chatBox-content-demo">

                        <div class='clearfloat'><div class='author-name'></div> <div class='left'> <div class='chat-avatars'><img src='../../image/my/hs.png' alt='头像'/></div><div class='chat-message'>给你看张图</div></div></div>

                        <div class="clearfloat">
                            <div class="author-name">
                                <!-- <small class="chat-date">2017-12-02 14:26:58</small> -->
                            </div>
                            <div class="left">
                                <div class="chat-avatars"><img src="../../image/my/hs.png" alt="头像"/></div>
                                <div class="chat-message">
                                    <img src="../../image/my/hs.png" alt="">
                                </div>
                            </div>
                        </div>

                        <div class="clearfloat">
                            <div class="author-name">
                                <small class="chat-date">2017-12-02 14:26:58</small>
                            </div>
                            <div class="right">
                                <div class="chat-message">嗯，适合做壁纸</div>
                                <div class="chat-avatars"><img src="../../image/my/hs.png" alt="头像"/></div>
                            </div>
                        </div>

                    </div>
                </div>
                <div class="chatBox-send">
                    <div class="div-textarea" contenteditable="true"></div>
                    <div>
                        <button id="chat-biaoqing" class="btn-default-styles">
                            <i class="iconfont icon-biaoqing"></i>
                        </button>
                        <button id="chat-fasong" class="btn-default-styles"><i class="iconfont icon-fasong"></i>
                        </button>
                        <label id="chat-tuxiang" title="发送图片" for="inputImage" class="btn-default-styles">
                            <div class="mainContainer">
                                <form method="post" enctype="multipart/form-data" id="form" action="upload">
                                  <div id="box2">
                                    <button class="select-button" id="select-button" sid=''><i class="iconfont icon-tuxiang"></i></button>
                                    <input class="file-input select2" type="file" id="inputImage" sid='' class="hidden" multiple="multiple"/>
                                  </div>
                                </form>
                            </div>
                        </label>
                        
                    </div>
                    <div class="biaoqing-photo">
                        <ul>
                            <li><span class="emoji-picker-image" style="background-position: -9px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -154px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -154px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -154px;"></span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<!-- <script src="js/jquery.min.js"></script> -->
<script src='../../js/jquery.js'></script>
<script type="text/javascript" src='../my/qiniu/qiniu.min.js'></script>
<script>
    document.title = "发噶是对方说的话"
    var speak;

    var token = document.cookie.slice(document.cookie.indexOf("=")+1)
    var lockReconnect = false;//避免重复连接
    var wsUrl = "wss://minitest.17jxyx.com/wss";
    var ws;
    var tt;
    function createWebSocket() {
      try {
        ws = new WebSocket(wsUrl);
        init();
      } catch(e) {
        console.log('catch');
        reconnect(wsUrl);
      }
    }
    function init() {
      ws.onclose = function () {
        console.log('链接关闭');
        reconnect(wsUrl);
      };
      ws.onerror = function() {
        console.log('发生异常了');
        reconnect(wsUrl);
      };
      ws.onopen = function (e) {
        var login_data = '{"type":"login","client_name":"kk","token":"'+token+'"}';
        console.log("websocket握手成功，发送登录数据:"+login_data);
        ws.send(login_data);
        console.log(e)
        //心跳检测重置
        heartCheck.start();
      };
      ws.onmessage = function (event) {
        //拿到任何消息都说明当前连接是正常的
        console.log(event);
        console.log(JSON.parse(event.data));
        if(JSON.parse(event.data).client_id){
            speak = JSON.parse(event.data).client_id
        }
        if(JSON.parse(event.data).type == "say"){
            var nei = JSON.parse(event.data).content
            var time = JSON.parse(event.data).time
            var message_type = JSON.parse(event.data).message_type
            if(message_type == 1){
                $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
                    "<div class=\"author-name\"><small class=\"chat-date\">"+time+"</small> </div> " +
                    "<div class=\"left\"><div class=\"chat-avatars\"><img src=\"../../image/my/hs.png\" alt=\"头像\" /></div> <div class=\"chat-message\"> " + nei + " </div> " +
                    " </div> </div>");
            }
            if(message_type == 3){
                 $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
                    "<div class=\"author-name\"><small class=\"chat-date\">"+time+"</small> </div> " +
                    "<div class=\"left\"> <div class=\"chat-avatars\"><img src=\"../../image/my/hs.png\" alt=\"头像\" /></div><div class=\"chat-message\"><img src=" + nei + "></div> " +
                    " </div> </div>");
              //聊天框默认最底部
            }
            $(document).ready(function () {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
        }
        // newDiv(event)
        heartCheck.start();
      }
    }
    function reconnect(url) {
      if(lockReconnect) {
        return;
      };

      lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      tt && clearTimeout(tt);
      tt = setTimeout(function () {
        createWebSocket(url);
        lockReconnect = false;
      }, 4000);
    }
    //心跳检测
    var heartCheck = {
      timeout: 30000,
      timeoutObj: null,
      serverTimeoutObj: null,
      start: function(){
        console.log('start');
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function(){
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          console.log('心跳');
          ws.send('{"type":"pong"}');
          self.serverTimeoutObj = setTimeout(function() {
            console.log(111);
            console.log(ws);
            ws.close();
            // createWebSocket();
          }, self.timeout);

        }, this.timeout)
      }
    }
    createWebSocket(wsUrl);

// {"type":"say","to_client":"' + wx.getStorageSync("usersPeoper").id + '","content":"' + inputVal+'","message_type":"1"}
    screenFuc();
    function screenFuc() {
        var topHeight = $(".chatBox-head").innerHeight();//聊天头部高度
        //屏幕小于768px时候,布局change
        var winWidth = $(window).innerWidth();
        if (winWidth <= 768) {
            var totalHeight = $(window).height(); //页面整体高度
            $(".chatBox-info").css("height", totalHeight - topHeight);
            var infoHeight = $(".chatBox-info").innerHeight();//聊天头部以下高度
            //中间内容高度
            $(".chatBox-content").css("height", infoHeight - 46);
            $(".chatBox-content-demo").css("height", infoHeight - 46);

            $(".chatBox-list").css("height", totalHeight - topHeight);
            $(".chatBox-kuang").css("height", totalHeight - topHeight);
            $(".div-textarea").css("width", winWidth - 106);
        } else {
            $(".chatBox-info").css("height", 495);
            $(".chatBox-content").css("height", 448);
            $(".chatBox-content-demo").css("height", 448);
            $(".chatBox-list").css("height", 495);
            $(".chatBox-kuang").css("height", 495);
            $(".div-textarea").css("width", 260);
        }
    }
    (window.onresize = function () {
        screenFuc();
    })();
    //未读信息数量为空时
    var totalNum = $(".chat-message-num").html();
    if (totalNum == "") {
        $(".chat-message-num").css("padding", 0);
    }
    $(".message-num").each(function () {
        var wdNum = $(this).html();
        if (wdNum == "") {
            $(this).css("padding", 0);
        }
    });


    //打开/关闭聊天框
    $(".chatBtn").click(function () {
        $(".chatBox").toggle(10);
    })
    $(".chat-close").click(function () {
        $(".chatBox").toggle(10);
    })
    //进聊天页面
    // $(".chat-list-people").each(function () {
    //     $(this).click(function () {
            var n = $(this).index();
            $(".chatBox-head-one").toggle();
            $(".chatBox-head-two").toggle();
            $(".chatBox-list").fadeToggle();
            $(".chatBox-kuang").fadeToggle();

            //传名字
            $(".ChatInfoName").text("实验");

            //传头像
            $(".ChatInfoHead>img").attr("src", "../../image/my/lytbdx.png");

            //聊天框默认最底部
            $(document).ready(function () {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
    //     })
    // });

    //返回列表
    $(".chat-return").click(function () {
        $(".chatBox-head-one").toggle(1);
        $(".chatBox-head-two").toggle(1);
        $(".chatBox-list").fadeToggle(1);
        $(".chatBox-kuang").fadeToggle(1);
    });

    //      发送信息
    $("#chat-fasong").click(function () {
        var textContent = $(".div-textarea").html().replace(/[\n\r]/g, '<br>')
        console.log(textContent)
        if (textContent != "") {
            ws.send('{"type":"say","to_client":"1","content":"' + textContent+'","message_type":"1"}');
            message_type1(textContent)
            // $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
            //     "<div class=\"author-name\"><small class=\"chat-date\">2017-12-02 14:26:58</small> </div> " +
            //     "<div class=\"right\"> <div class=\"chat-message\"> " + textContent + " </div> " +
            //     "<div class=\"chat-avatars\"><img src=\"../../image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
            //发送后清空输入框
            $(".div-textarea").html("");
            //聊天框默认最底部
            $(document).ready(function () {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
        }
    });

    //      发送表情
    $("#chat-biaoqing").click(function () {
        $(".biaoqing-photo").toggle();
    });
    $(document).click(function () {
        $(".biaoqing-photo").css("display", "none");
    });
    $("#chat-biaoqing").click(function (event) {
        event.stopPropagation();//阻止事件
    });

    $(".emoji-picker-image").each(function () {
        $(this).click(function () {
            var bq = $(this).parent().html();
            console.log(bq)
            $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
                "<div class=\"author-name\"><small class=\"chat-date\">2017-12-02 14:26:58</small> </div> " +
                "<div class=\"right\"> <div class=\"chat-message\"> " + bq + " </div> " +
                "<div class=\"chat-avatars\"><img src=\"../../image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
            //发送后关闭表情框
            $(".biaoqing-photo").toggle();
            //聊天框默认最底部
            $(document).ready(function () {
                $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
            });
        })
    });
    function message_type1(textContent){
        $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
                "<div class=\"author-name\"><small class=\"chat-date\">2017-12-02 14:26:58</small> </div> " +
                "<div class=\"right\"> <div class=\"chat-message\"> " + textContent + " </div> " +
                "<div class=\"chat-avatars\"><img src=\"../../image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
    }
    function message_type3(srcs){
         $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
            "<div class=\"author-name\"><small class=\"chat-date\">2017-12-02 14:26:58</small> </div> " +
            "<div class=\"right\"> <div class=\"chat-message\"><img src=" + srcs + "></div> " +
            "<div class=\"chat-avatars\"><img src=\"../../image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
    }

    // //      发送图片
    // function selectImg(pic) {
    //     if (!pic.files || !pic.files[0]) {
    //         return;
    //     }
    //     var reader = new FileReader();
    //     reader.onload = function (evt) {
    //         var images = evt.target.result;
    //         $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
    //             "<div class=\"author-name\"><small class=\"chat-date\">2017-12-02 14:26:58</small> </div> " +
    //             "<div class=\"right\"> <div class=\"chat-message\"><img src=" + images + "></div> " +
    //             "<div class=\"chat-avatars\"><img src=\"../../image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
    //         //聊天框默认最底部
    //         $(document).ready(function () {
    //             $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
    //         });
    //     };
    //     reader.readAsDataURL(pic.files[0]);

    // }



 //图片上传
  $.ajax({
    url: "https://minitest.17jxyx.com/api/v1/token/file/goods",
    datagoods:"json",
    beforeSend: function(request) {
        request.setRequestHeader("token",token);
    },
    success: function(res){
      console.log(res)
      var token = res.token;
      var domain = res.url;
      var config = {
        useCdnDomain: true,
        disableStatisticsReport: true,
        retryCount: 6,
        region: qiniu.region.z2
      };
      var putExtra = {
        fname: "",
        params: {},
        mimeType: null
      };
      function nam(){
        console.log(this)
      }
      uploadWithSDK(token, putExtra, config, domain,'goods');
    }
  })
  function uploadWithSDK(token, putExtra, config, domain, typename) {
    // 切换tab后进行一些css操作

      $(".select2").unbind("change").bind("change",function(){
          var types = this.getAttribute("sid")
          var file = this.files[0]
          var finishedAttr = [];
          var compareChunks = [];
          var observable;
            var timestamp;
          if (file) {
            var key = file.name;
            var fr = new FileReader();
            fr.readAsDataURL(file);
              // 添加上传dom面板
              // var board = addUploadBoard(file, config, key,'base64', types, "");
              // if (!board) {
              //   return;
              // }
        // $("#uploading").click(function(){
                putExtra.params["x:name"] = "goods"
                // board.start = true;
              // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
                var error = function(err) {

                  console.log(err);
                  alert("上传出错")
                };
                var complete = function(res) {

                  console.log(res)
                  var srcs = "http://resource.17jxyx.com/"+res.key
                  ws.send('{"type":"say","to_client":"1","content":"' + srcs+'","message_type":"3"}');
                   message_type3(srcs)
                  // $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
                  //   "<div class=\"author-name\"><small class=\"chat-date\">2017-12-02 14:26:58</small> </div> " +
                  //   "<div class=\"right\"> <div class=\"chat-message\"><img src=" + srcs + "></div> " +
                  //   "<div class=\"chat-avatars\"><img src=\"../../image/my/hs.png\" alt=\"头像\" /></div> </div> </div>");
                //聊天框默认最底部
                $(document).ready(function () {
                    $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
                });
                  // console.log("http://resource.17jxyx.com/"+res.key)



                };

                var next = function(response) {
                  var chunks = response.chunks||[];
                  var total = response.total;
                  // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
                  for (var i = 0; i < chunks.length; i++) {
                    if (chunks[i].percent === 0 || finishedAttr[i]){
                      continue;
                    }
                    if (compareChunks[i].percent === chunks[i].percent){
                      continue;
                    }
                    if (chunks[i].percent === 100){
                      finishedAttr[i] = true;
                    }
                  }
                  compareChunks = chunks;
                };

                var subObject = { 
                  next: next,
                  error: error,
                  complete: complete
                };
                var subscription;
                var names = file.name
                var rank1 = names.indexOf('.');
                var rank3 = rank1;
                var rank = names.slice(rank3);
                var ranks = token.slice(10,25);
                var timetamp = Date.parse(new Date()) 
                var key = typename+"/"+timetamp+ranks+rank
                console.log(timetamp)
                console.log(key)

             // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(file, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);

        }
    })
  }
// bqxtb01.png

</script>

</body>
</html>
